package com.baizhi.service.impl;

import com.baizhi.dao.BzAdminMapper;
import com.baizhi.entity.BzAdmin;
import com.baizhi.service.IBzAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lby
 * @since 2020-09-24
 */
@Slf4j
@Service
public class BzAdminServiceImpl extends ServiceImpl<BzAdminMapper, BzAdmin> implements IBzAdminService , UserDetailsService {
    @Autowired
    private BzAdminMapper bzAdminMapper;
    //        1.创建一个查询条件构造器对象  泛型 被查询实体类
    QueryWrapper<BzAdmin> wrapper = new QueryWrapper<>();

    @Override
    public List<BzAdmin> selectAll() {
        return bzAdminMapper.selectList(null);
    }

    @Override
    public Map showPageAdmin(Integer page, Integer limit) {
        //创建分页对象 构造分页参数
        Page<BzAdmin> pageObj = new Page<>(page,limit);
        //调用分页查询的方法 selectPage
        Page<BzAdmin> adminPage = bzAdminMapper.selectPage(pageObj, null);
        //获取数据总条数
        long total = adminPage.getTotal();
        System.out.println("total = " + total);
        //得到查询的真实数据
        Map map = new HashMap<>();
        List<BzAdmin> admins = adminPage.getRecords();
        map.put("count",total);
        map.put("admins",admins);
        return map;
    }

    @Override
    public BzAdmin login(String username, String password) {
        wrapper.eq("username",username);
        BzAdmin b =new BzAdmin();
        List<BzAdmin> bzAdmins = bzAdminMapper.selectList(wrapper);
        for (BzAdmin bzAdmin:bzAdmins
             ) {
            if (bzAdmin!=null&& bzAdmin.getPassword().equals(password)){
                b=bzAdmin;
            }
        }
        return b;
    }

    /**
     * 该方法就是SpringSecurity预留的查询数据库的方法 需要我们自己写实现
     *
     * 形参是 用户名（用户在浏览器上输入的用户名）
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info(s+"查询数据库");
        BzAdmin admin = getOne(
                new QueryWrapper<BzAdmin>()
                        .eq("username", s)
        );
        if (admin == null) {
            log.error(s+"不存在");
            throw new UsernameNotFoundException(s+"不存在");
        }
        return admin;
    }
}
